import Vue from 'vue'
import Vuex from 'vuex'
import {nanoid} from 'nanoid'
import axios from 'axios'

Vue.use(Vuex)
//响应组件动作
const actions = {
	async getOneNewsFromServer({commit}){
		try {
			//发请求获取数据
			const result = await axios.get('https://api.uixsj.cn/hitokoto/get?type=social')
			//包装一个news对象
			const news = {id:nanoid(),title:result.data}
			//联系“大厨”添加一条新闻
			commit('ADD_NEWS',news)
		} catch (error) {
			alert(error)
		}
	}
}
//修改数据
const mutations = {
	ADD_PERSON(state,personObj){
		state.persons.unshift(personObj)
	},
	ADD_NEWS(state,newsObj){
		state.newsList = [newsObj,...state.newsList]
	}
}
//数据
const state = {
	describe:'该案例是联系vuex最基本的语法',
	persons:[
		{id:'i6t76fsda56t76a',name:'强强',age:108},
		{id:'joisduf8dsfsdfs',name:'秋秋',age:18}
	],
	newsList:[
		{id:'austrd6strd7',title:'《这种致癌物，你天天在吃》'},
		{id:'iusda988udss',title:'《如何一夜暴富》'}
	]
}

//创建store
const store = new Vuex.Store({
	actions,
	mutations,
	state
})

//暴露store
export default store